<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Collections.Specialized" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="OSGeo.MapGuide" %>

<!-- #Include File="markupschemafactory.aspx -->
<!-- #Include File="../../utilityfunctions.aspx -->

<script language="c#" runat="server">
    public class MarkupManager
    {
        public const String LL84WKT = "LOCAL_CS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]";
	    NameValueCollection args = null;
	    private MgSiteConnection site = null;

   	    public MarkupManager(NameValueCollection incomingArgs)
    	{
    	    this.args = incomingArgs;
    	    this.site = new MgSiteConnection();
    	    this.site.Open(new MgUserInformation(GetParameter(this.args, "SESSION")));
    	}
    	
	    public Hashtable GetAvailableMarkup()
	    {
		    Hashtable markup = new Hashtable();
    		
	        MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
            MgResourceIdentifier resourceID = new MgResourceIdentifier("Library://Markup/");
    		
		    try
		    {		
			    MgByteReader byteReader = resourceService.EnumerateResources(resourceID, 1, "LayerDefinition");
			    String resourceListXML = byteReader.ToString();
    			
			    XmlDocument doc = new XmlDocument();
			    doc.LoadXml(resourceListXML);
			    XmlNodeList nodeList = doc.GetElementsByTagName("ResourceId");
    			
			    foreach (XmlElement element in nodeList)
			    {
                    MgResourceIdentifier resourceId = new MgResourceIdentifier(element.InnerText);
				    markup[resourceId.ToString()] = resourceId.GetName();
			    }
		    }
		    catch (MgResourceNotFoundException mge)
		    {
			    // If the Library://Markup folder does not exist, create it.
			    resourceService.SetResource(resourceID, null, null); 
		    }
    		
		    return markup;
	    }
    		
	    public void OpenMarkup()
	    {
            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
    		
            MgMap map = new MgMap();
            map.Open(resourceService, GetParameter(this.args, "MAPNAME"));

		    // Create the Layer Groups

		    MgLayerGroup markupGroup = null;
		    MgLayerGroupCollection layerGroups = map.GetLayerGroups();
		    if (layerGroups.Contains("_Markup"))
		    {
			    markupGroup = layerGroups.GetItem("_Markup");
		    }
		    else
		    {
			    markupGroup = new MgLayerGroup("_Markup");
			    markupGroup.SetVisible(true);
			    markupGroup.SetLegendLabel("Markup");
			    markupGroup.SetDisplayInLegend(false);
			    layerGroups.Add(markupGroup);
		    }

		    // Add the Markup Layer
    		
		    MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "MARKUPLAYER"));
		    MgLayer markupLayer = new MgLayer(markupLayerResId, resourceService);
		    markupLayer.SetName("_" + markupLayerResId.GetName());
		    markupLayer.SetLegendLabel(markupLayerResId.GetName());
		    markupLayer.SetDisplayInLegend(false);
		    markupLayer.SetSelectable(true);
		    markupLayer.SetGroup(markupGroup);
		    map.GetLayers().Insert(0, markupLayer);
    		
		    map.Save(resourceService);
	    }

	    public void CloseMarkup()
	    {
            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
    		
            MgMap map = new MgMap();
            map.Open(resourceService, GetParameter(this.args, "MAPNAME"));

		    // Add the Markup Layer

		    MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "OPENMARKUP"));
		    int index = map.GetLayers().IndexOf("_" + markupLayerResId.GetName());
		    map.GetLayers().RemoveAt(index);
    		
		    map.Save(resourceService);
	    }
    	
	    public void CreateMarkup()
	    {
            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
		    MgFeatureService featureService = (MgFeatureService)this.site.CreateService(MgServiceType.FeatureService);

            MgMap map = new MgMap();
            map.Open(resourceService, GetParameter(args, "MAPNAME"));

		    // Create the Markup Feature Source (SDF)

		    MgResourceIdentifier markupSdfResId = new MgResourceIdentifier("Library://Markup/" + GetParameter(this.args, "MARKUPNAME") + ".FeatureSource");
    		
		    MgFeatureSchema markupSchema = MarkupSchemaFactory.CreateMarkupSchema();
		    MgCreateSdfParams sdfParams = new MgCreateSdfParams("XY-M", map.MapSRS, markupSchema);
		    featureService.CreateFeatureSource(markupSdfResId,sdfParams);

		    // Create the Markup Layer Definition

		    String hexFgTransparency = String.Format("{0:X2}", 255 * (100 - Int32.Parse(GetParameter(this.args, "FILLTRANSPARENCY"))) / 100); // Convert % to an alpha value
		    String hexBgTransparency = GetParameter(this.args, "FILLBACKTRANS").Length > 0 ? "FF" : "00";							 // All or nothing
		    String bold = GetParameter(this.args, "LABELBOLD").Length > 0 ? "true" : "false";
		    String italic = GetParameter(this.args, "LABELITALIC").Length > 0 ? "true" : "false";
		    String underline = GetParameter(this.args, "LABELUNDERLINE").Length > 0 ? "true" : "false";
    		
            String markupLayerDefinition = File.ReadAllText(GetBasePath() + "Extensions\\markup\\templates\\markuplayerdefinition.xml");
            markupLayerDefinition = String.Format(markupLayerDefinition, 
			    markupSdfResId.ToString(),						                //<ResourceId> - Feature Source
			    GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Mark Label
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Mark Label Size
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Mark Label Size
			    "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Mark Label
			    "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Mark Label
			    GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Mark Label
			    bold,												            //<Bold> - Mark Label
			    italic,											                //<Bold> - Mark Label
			    underline,											            //<Underlined> - Mark Label
			    GetParameter(this.args, "MARKERSIZEUNITS"),						//<Unit> - Mark
			    GetParameter(this.args, "MARKERSIZE"),							//<SizeX> - Mark
			    GetParameter(this.args, "MARKERSIZE"),							//<SizeY> - Mark
			    GetParameter(this.args, "MARKERTYPE"),							//<Shape> - Mark
			    "FF" + GetParameter(this.args, "MARKERCOLOR"),					//<ForegroundColor> - Mark
			    "FF" + GetParameter(this.args, "MARKERCOLOR"),					//<Color> - Mark
			    GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Line Label
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Line Label Size
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Line Label Size
			    "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Line Label
			    "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Line Label
			    GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Line Label
			    bold,												            //<Bold> - Line Label
			    italic,											                //<Bold> - Line Label
			    underline,											            //<Underlined> - Line Label			
			    GetParameter(this.args, "LINEPATTERN"),							//<LineStyle> - Line
			    GetParameter(this.args, "LINETHICKNESS"),						//<Thickness> - Line
			    "FF" + GetParameter(this.args, "LINECOLOR"),					//<Color> - Line
			    GetParameter(this.args, "LINESIZEUNITS"),						//<Unit> - Line
			    GetParameter(this.args, "LABELSIZEUNITS"),						//<Unit> - Polygon Label
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeX> - Polygon Label Size
			    GetParameter(this.args, "LABELFONTSIZE"),						//<SizeY> - Polygon Label Size
			    "FF" + GetParameter(this.args, "LABELFORECOLOR"),				//<ForegroundColor> - Polygon Label
			    "FF" + GetParameter(this.args, "LABELBACKCOLOR"),				//<BackgroundColor> - Polygon Label
			    GetParameter(this.args, "LABELBACKSTYLE"),						//<BackgroundStyle> - Polygon Label
			    bold,												            //<Bold> - Polygon Label
			    italic,											                //<Bold> - Polygon Label
			    underline,											            //<Underlined> - Polygon Label
			    GetParameter(this.args, "FILLPATTERN"), 						//<FillPattern> - Fill
			    hexFgTransparency + GetParameter(this.args, "FILLFORECOLOR"), 	//<ForegroundColor> - Fill
			    hexBgTransparency + GetParameter(this.args, "FILLBACKCOLOR"), 	//<BackgroundColor> - Fill
			    GetParameter(this.args, "BORDERPATTERN"),						//<LineStyle> - Fill
			    GetParameter(this.args, "BORDERTHICKNESS"), 					//<Thickness> - Fill
			    "FF" + GetParameter(this.args, "BORDERCOLOR"), 					//<Color> - Fill
                GetParameter(this.args, "BORDERSIZEUNITS"), 					//<Unit> - Fill
                "concat(&apos;"+GetParameter(this.args, "MARKUPURL")+"&apos;, concat(&apos;?key=&apos;, &quot;ID&quot;))"); //<Url> - url link
    		
		    MgByteReader byteReader = new MgByteReader(markupLayerDefinition, "text/xml");
		    resourceService.SetResource(new MgResourceIdentifier("Library://Markup/" + GetParameter(this.args, "MARKUPNAME") + ".LayerDefinition"), byteReader, null);
	    }
    	
	    public void DeleteMarkup()
	    {
		    MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);

		    MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(args, "MARKUPLAYER"));
		    MgResourceIdentifier markupSdfResId = new MgResourceIdentifier("Library://Markup/" + markupLayerResId.GetName() + ".FeatureSource");

		    resourceService.DeleteResource(markupLayerResId);
		    resourceService.DeleteResource(markupSdfResId);
	    }

	    public Hashtable GetOpenMarkup()
	    {
		    Hashtable openMarkup = new Hashtable();
    		
		    MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);
    		
	        MgMap map = new MgMap();
	        map.Open(resourceService, GetParameter(this.args, "MAPNAME"));
    		
		    MgLayerGroupCollection layerGroups = map.GetLayerGroups();
		    if (layerGroups.Contains("_Markup"))
		    {
			    MgLayerCollection layers = map.GetLayers();
    			
			    for (int i = 0; i < layers.GetCount(); i++)
			    {
		            MgLayer layer = (MgLayer) layers.GetItem(i);
				    if ((layer.GetGroup() != null) && (layer.GetGroup().GetName().Equals("_Markup")))
				    {
					    openMarkup["Library://Markup/" + layer.GetLegendLabel() + ".LayerDefinition"] = layer.GetLegendLabel();
				    }		
			    }
		    }				
		    return openMarkup;
	    }	
    }
</script>